package com.ruoyi.lvlian.controller;

import java.util.*;

import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.MD5Utils;
import com.ruoyi.common.core.utils.PhoneNumberValidator;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.OrderTrackInfo;
import com.ruoyi.lvlian.dto.OrderInfoDto;
import com.ruoyi.lvlian.service.ICommonService;
import com.ruoyi.lvlian.util.Null2StrUtil;
import com.ruoyi.lvlian.util.OrderNumberGenerator;
import com.ruoyi.lvlian.vo.OrderInfoVo;
import com.ruoyi.lvlian.vo.WarehouseInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.lvlian.domain.OrderInfo;
import com.ruoyi.lvlian.service.IOrderInfoService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.github.pagehelper.PageInfo;

@Api(value = "跟单信息", tags = "跟单信息Controller")
@RestController
@RequestMapping("/orderInfo")
public class OrderInfoController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(OrderInfoController.class);
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private ICommonService iCommonService;


    @ApiOperation("获取跟单信息详细信息")
    //@RequiresPermissions("lvlian:orderInfo:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(orderInfoService.selectOrderInfoById(id));
    }

    @ApiOperation("获取跟单信息详细信息getInfoById")
    @GetMapping("/getInfoById")
    public AjaxResult getInfoById(@ApiParam(value = "跟单ID", required = true) @RequestParam(value = "id") String id) {
        return success(orderInfoService.selectOrderInfoById(id));
    }


/*    @ApiOperation("新增跟单信息")
    //@RequiresPermissions("lvlian:orderInfo:add")
    @Log(title = "跟单信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody OrderInfo orderInfo) {
        log.info( orderInfo.toString());
        if (!"success".equalsIgnoreCase(validateInData(orderInfo))) {
            return error(validateInData(orderInfo));
        }

        return toAjax(orderInfoService.insertOrderInfo(orderInfo));
    }*/


    private String validateInData(OrderInfo orderInfo) {

        if (StringUtils.isEmpty(orderInfo.getBusinessUserPhone())) {
            return "跟车方电话不能为空";
        }
        if (!PhoneNumberValidator.isValidPhoneNumber(orderInfo.getBusinessUserPhone())) {
            return "跟车方电话无效";
        }


        if (StringUtils.isEmpty(orderInfo.getSellerPhone())) {
            return "供应商电话号码不能为空";
        }

        if (!PhoneNumberValidator.isValidPhoneNumber(orderInfo.getSellerPhone())) {
            return "供应商电话号码无效";
        }


        if (StringUtils.isEmpty(orderInfo.getBuyerPhone())) {
            return "购买方电话号码不能为空";
        }

        if (!PhoneNumberValidator.isValidPhoneNumber(orderInfo.getBuyerPhone())) {

            return "购买方电话号码无效";
        }

        if (StringUtils.isNotEmpty(orderInfo.getDriverPhone()) && !PhoneNumberValidator.isValidPhoneNumber(orderInfo.getDriverPhone())) {
            return "司机电话号码无效";
        }


/*        if (StringUtils.isNotEmpty(orderInfo.getDriverStartTime()) && !DateUtils.isValidDateTime(orderInfo.getDriverStartTime())) {
            return "司机开始时间无效";
        }
        if (StringUtils.isNotEmpty(orderInfo.getDriverStartTime()) && !DateUtils.isValidDateTime(orderInfo.getDriverStartTime())) {
            return "司机开始时间无效";
        }
        if (StringUtils.isNotEmpty(orderInfo.getBusinessUserStartTime()) && !DateUtils.isValidDateTime(orderInfo.getBusinessUserStartTime())) {
            return "业务员开始时间无效";
        }*/


        if (StringUtils.isEmpty(orderInfo.getBusinessUserCompanyName()) || StringUtils.isEmpty(orderInfo.getSellerCompanyName())
                || StringUtils.isEmpty(orderInfo.getBuyerCompanyName()) || StringUtils.isEmpty(orderInfo.getBusinessUserName())) {
            return "公司名称或者业务人员不能为空";
        }
        return "success";
    }

    @ApiOperation("新增 / 修改跟单信息")
    //@RequiresPermissions("lvlian:orderInfo:edit")
    @Log(title = "跟单信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated OrderInfo orderInfo) {
        log.info(orderInfo.toString());
         if (!"success".equalsIgnoreCase(validateInData(orderInfo))   && orderInfo.getBusinessUserStatus()!=1 ) {
            return error(validateInData(orderInfo));
        }
        String s = orderInfoService.updateOrderInfo(orderInfo);
        Object obj = new String(s);
        return success(obj);
    }


    @ApiOperation("查询业务人员在不同时间范围内的跟单数量")
    @PostMapping("/countOrderByTimeRanges")
    public AjaxResult countOrderByTimeRanges(@Validated @RequestBody OrderInfoDto orderInfoDto) {
        List<HashMap<String, Object>> orderCounts = orderInfoService.countOrderByTimeRanges(orderInfoDto);
        return AjaxResult.success(orderCounts);
    }


    @ApiOperation("查询司机端跟单数量")
    @PostMapping("/countOrderByDriver")
    public AjaxResult countOrderByDriver(@Validated @RequestBody OrderInfoDto orderInfoDto) {
        List<HashMap<String, Object>> orderCounts = orderInfoService.countOrderByDriver(orderInfoDto);
        return AjaxResult.success(orderCounts);
    }


    @ApiOperation("查询各自的跟单数量 ,period 周期本月传30")
    @PostMapping("/queryOrderCnt")
//    @RequestParam(value = "vehicleNo", required = true, defaultValue = "黑AN8721")
    public AjaxResult queryOrderCnt(@Validated @RequestBody OrderInfoDto orderInfoDto) {
        if (StringUtils.isEmpty(orderInfoDto.getBusinessUserPhone()) && StringUtils.isEmpty(orderInfoDto.getDriverPhone())) {
            return error("businessUserPhone 和 司机手机号码不能同时为空");
        }
        if (StringUtils.isNotEmpty(orderInfoDto.getDriverPhone()) && !PhoneNumberValidator.isValidPhoneNumber(orderInfoDto.getDriverPhone())) {
            return error("司机手机号码无效");
        }

//        if (StringUtils.isEmpty(orderInfoDto.getPeriod())) {
//            orderInfoDto.setPeriod(null);
//        }

        int cnt = orderInfoService.queryOrderCnt(orderInfoDto.getBusinessUserPhone(), orderInfoDto.getDriverPhone(), orderInfoDto.getPeriod());

        return AjaxResult.success(cnt);
    }


    @ApiOperation("小程序查询 手机必传 首页查询跟车方的跟单  司机方也是用这个接口，通过手机号码查")
    @GetMapping("/queryOrderInfoByUserPhone")
    public TableDataInfo queryOrderInfoByUserPhone( OrderInfoDto orderInfoDto) {
        if(StringUtils.isEmpty(orderInfoDto.getBusinessUserStartTime() ) || orderInfoDto.getBusinessUserStartTime()==null || orderInfoDto.getBusinessUserStartTime().length()<5){
            orderInfoDto.setBusinessUserStartTime(null);
        }
        if (StringUtils.isEmpty(orderInfoDto.getBusinessUserPhone()) && StringUtils.isEmpty(orderInfoDto.getDriverPhone())) {
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);

            rspData.setMsg("业务人员或者司机的手机号码不能同时为空");
            return rspData;
        }
        if (StringUtils.isNotEmpty(orderInfoDto.getBusinessUserPhone()) && !PhoneNumberValidator.isValidPhoneNumber(orderInfoDto.getBusinessUserPhone())) {
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("业务人员手机号码不对");
            return rspData;
        }
        if (StringUtils.isNotEmpty(orderInfoDto.getDriverPhone()) && !PhoneNumberValidator.isValidPhoneNumber(orderInfoDto.getDriverPhone())) {
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("业务人员手机号码不对");
            return rspData;
        }

            List<String> orgCodes = iCommonService.queryCurrentOrgCode(SecurityUtils.getUserId());
            if(orgCodes.size()==0){
                return getDataTable(new ArrayList<WarehouseInfoVo>() )  ;
            }
            if (Objects.isNull(orderInfoDto.getOrgCodes()) || orderInfoDto.getOrgCodes().isEmpty()) {
                orgCodes.removeIf(code -> code.length() != 8);
                orderInfoDto.setOrgCodes( orgCodes);
            }




//        司机可能接了很多公司的活 ，notYet

        startPage();
        List<OrderInfoVo> list = orderInfoService.queryOrderInfoByUserPhone(orderInfoDto);


        return getDataTable(list);
    }





    @ApiOperation("小程序查询司机端,根据司机号码查询司机的跟单")
    @GetMapping("/queryOrderInfoByDriverPhone")
    public TableDataInfo queryOrderInfoByDriverPhone( OrderInfoDto orderInfoDto) {
        if (StringUtils.isEmpty(orderInfoDto.getDriverPhone())) {
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("司机的手机号码不能为空");
            return rspData;
        }
        if (StringUtils.isNotEmpty(orderInfoDto.getDriverPhone()) && !PhoneNumberValidator.isValidPhoneNumber(orderInfoDto.getDriverPhone())) {
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("司机的手机号码号码不对");
            return rspData;
        }


        startPage();
        List<OrderInfoVo> list = orderInfoService.queryOrderInfoByDriverPhone(orderInfoDto);
        try {
            Null2StrUtil.sanitizeObjectList(list);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        // 获取分页信息
        PageInfo<OrderInfoVo> pageInfo = new PageInfo<>(list);
        int pageNum = pageInfo.getPageNum();  // 当前页码
        int pageSize = pageInfo.getPageSize(); // 每页显示记录数
        long total = pageInfo.getTotal();    // 总记录数

/*        System.out.println("PageNum: " + pageNum);
        System.out.println("PageSize: " + pageSize);
        System.out.println("Total: " + total);*/

        return getDataTable(list);
    }


    @ApiOperation("查询跟单信息列表")
    //@RequiresPermissions("lvlian:orderInfo:list")
    @GetMapping("/list")
    public R<TableDataInfo>  list(OrderInfoDto orderInfo) {
        if ("all".equalsIgnoreCase(orderInfo.getBusinessUserStatus())) {
            orderInfo.setBusinessUserStatus(null);
        }
        if (SecurityUtils.getUserId() == 1) {
            orderInfo.setOrgCodes(new ArrayList<>(Arrays.asList("50000000")));
        } else {
            List<String> orgCodes = iCommonService.queryCurrentOrgCode(SecurityUtils.getUserId());

            if ((Objects.isNull(orderInfo.getOrgCodes()) || orderInfo.getOrgCodes().isEmpty()) && Objects.isNull(orgCodes)) {
                return R.fail("暂未分配账本");
            }
            if (Objects.isNull(orderInfo.getOrgCodes()) || orderInfo.getOrgCodes().isEmpty()) {
                orgCodes.removeIf(code -> code.length() != 8);
                orderInfo.setOrgCodes(orgCodes);
            }
        }
        startPage();
        List<OrderInfoVo> list = orderInfoService.selectOrderInfoList(orderInfo);
        return R.ok(getDataTable(list));
    }


    @PostMapping("/remove")
    @Log(title = "订单删除", businessType = BusinessType.DELETE)
    public AjaxResult remove(@RequestBody String[] ids) {
        if( ids == null || ids.length == 0  ){
            return error("未选中") ;
        }
        return toAjax(orderInfoService.deleteOrderInfoByIds(ids));
    }


    @ApiOperation("获取跟单轨迹")
    @GetMapping("/queryOrderTrackInfoList")
    public TableDataInfo list(@ApiParam(value = "跟单ID", required = true) @RequestParam(value = "orderId") String orderId ,@ApiParam(value = "轨迹分类", required = false) @RequestParam(value = "category" ) String category ) {
//        , defaultValue = "bussinessUser"
        startPage();
        List<OrderTrackInfo> list = orderInfoService.queryOrderTrackInfoList(orderId ,category);
        return getDataTable(list);
    }


    @ApiOperation("校验车辆跟单权限")
    @GetMapping("/validateVehicleOrderPermission")
    public AjaxResult validateVehicleOrderPermission(@ApiParam(value = "司机手机号", required = true) @RequestParam(value = "driverPhone") String driverPhone ,
                                                     @ApiParam(value = "车牌号码", required = true) @RequestParam(value = "plateNo") String plateNo) {
        // 调用服务层校验车辆跟单权限
        boolean hasPermission = orderInfoService.validateVehicleOrderPermission(driverPhone ,plateNo );
        return AjaxResult.success(hasPermission);
    }


    @ApiOperation("生成跟单编号")
    @GetMapping("/generateOrderNumber")
    public AjaxResult generateOrderNumber() {
        return AjaxResult.success(OrderNumberGenerator.generateOrderNumber());
    }
}
